$(document).ready(function() {
	var searchBox = $("#search-box"),
		selected = {"entity": [], "value": []},
		results = {"entity": [], "value": []},
		workspaces = {
			"value": $("#value-workspace"),
			"entity": $("#entity-workspace"),
			"entity-group": $("#entity-group-workspace")
		};
	
	$.ui.autocomplete.prototype._renderMenu = function(ul, items) {
		var self = this;
		
		$.each(items, function(idx, objs) {
			var list = $("<div/>").appendTo(ul).addClass("menu-list");
			
			$.each(objs, function(i, item) {
				if (typeof item == "object") {
					self._renderItem(list, item);
				}
			});
		});
	};
	
	$.ui.autocomplete.prototype._renderItem = function(ul, item) {
		return $("<div/>")
			.data("item.autocomplete", item)
			.addClass("ui-menu-item")
			.append($("<a/>", {
				text: item[isValue(item) ? "value" : "all"]
			})).appendTo(ul);
	};
	
	function requestData(type) {
		var d = $.Deferred();
		
		return $.getJSON("http://localhost:8000/" +
			type + "/?callback=?",
			{q: searchBox.val()}, function(resData) {
				results[type] = resData.data;
			}).done(d.resolve);
	}
	
	// schedule, course, person
	
	searchBox.autocomplete({
		source: function(req, resp) {
			$.when(requestData("entity"), requestData("value"))
				.done(function() {
					resp(results);
				});
		},
		select: function(e, ui) {
			var t = type(ui.item);
			
			selected[t].push(ui.item);
			searchBox.val("");
			
			return false;
		}
	});
	
	searchBox.bind("webkitspeechchange", function() {
		searchBox.autocomplete("search", $(this).value);
	});
	
	searchBox.focus();
})
